from datetime import datetime
from typing import Any

from fastapi import APIRouter, Depends
from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy import select, or_
from sqlalchemy.ext.asyncio import AsyncSession

from common import logger, custom_exc
from core.config import settings
from models.user import User
from auth.security import verify_password, create_access_token
from dependencies.deps import get_db
from schemas.response import resp

router = APIRouter(tags=["认证与授权"])


# 账号密码登录(包含邮箱登录、手机号登录)
@router.post("/login", summary="登录认证")
async def login_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
    """
    实现OAuth2密码登录
    :param form_data:
    :param db:
    :return:
    """
    result = await db.execute(
        select(User).where(or_(User.username == form_data.username, User.email == form_data.username, User.phone == form_data.username)))
    user = result.scalars().first()
    if not user:
        raise custom_exc.TokenAuthError(err_desc="账号或密码错误")
    if not verify_password(form_data.password, user.password):
        raise custom_exc.TokenAuthError(err_desc="账号或密码错误")
    # 更新最后登录时间
    user.last_login = datetime.now()
    try:
        # 更新用户信息到数据库
        await db.merge(user)
        logger.info(f"User {user.username} last login updated to {user.last_login}")
    except Exception as e:
        await db.rollback()
        logger.error(f"Failed to update last login time for user {user.username}: {e}")
        raise custom_exc.DatabaseError(err_desc="数据库操作失败")
    return resp.ok(data={"access_token": create_access_token({"id": user.id, "username": user.username}),
                         "token_type": "bearer"})
# TODO: 手机号验证码登录
# TODO: 微信扫码登录
# async def login_access_token(
#         *,
#         req: sys_user_schema.UserPhoneAuth,
# ) -> Any:
#     """
#     实现登录认证获取token
#     :param req:
#     :return:
#     """
#
#     # 验证用户 简短的业务可以写在这里
#     # user = User.single_by_phone(phone=req.username)
#     # if not user:
#     #     return resp.fail(resp.DataNotFound.set_msg("账号或密码错误"))
#     #
#     # if not security.verify_password(req.password, user.password):
#     #     return resp.fail(resp.DataNotFound.set_msg("账号或密码错误"))
#     #
#     # access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
#     #
#     # # 登录token 存储了user.id
#     # return resp.ok(data={
#     #     "token": security.create_access_token(user.id, expires_delta=access_token_expires),
#     # })
#
#     # 复杂的业务逻辑建议 抽离到 logic文件夹下
#     token = UserLogic().user_login_logic(req.username, req.password)
#     return resp.ok(data={"token": token})
